using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Collections.Specialized;

using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
using AMStudio.Script;

namespace IPTE.Manager
{   

    public partial class RunTi44meDB
    {
        public static Machine_Err[] errors;
        public static Machine_Err[] conditions;

        public static List<Test_Item> TestItems = new List<Test_Item>();
        public static SortedList TestResults = new SortedList();

        public static void SetLanguage(string culture)
        {
            try
            {
                if (RuntimeConfig.Errors == null)
                {
                    return;
                }

                //string modulePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
                //string ini_file = Path.Combine(modulePath, "Cfg\\RSU.ini");
                //Fany.Libs.IniFile iniL = new Fany.Libs.IniFile(ini_file);
                //bool errorprioritysupport = iniL.ReadBoolean("Main", "ErrorPrioritySupport", false);
                bool errorprioritysupport = true;
                errors = new Machine_Err[RuntimeConfig.Errors.Rows.Count];
                for (int i = 0; i < RuntimeConfig.Errors.Rows.Count; i++)
                {
                    DataRow row = RuntimeConfig.Errors.Rows[i];
                    if (string.IsNullOrEmpty(row[0].ToString()))
                        break;
                    int index = int.Parse(row["Index"].ToString());
                    string code = row["Code"].ToString();
                    string text = row["Message"].ToString();
                    int st = int.Parse(row["Station"].ToString());
                    int pr = int.Parse(row["Port"].ToString());
                    int bit = int.Parse(row["Bit"].ToString());
                    int priority = 0;
                    string hardware = string.Empty;
                    string comments = string.Empty;
                    if (errorprioritysupport)
                    {
                        priority = int.Parse(row["Priority"].ToString());
                        hardware = row["Hardware"].ToString();
                        comments = row["Comments"].ToString();
                    }
                    errors[index] = new Machine_Err(code, text, st, pr, bit, priority, hardware, comments);
                }

                conditions = new Machine_Err[RuntimeConfig.Conditions.Rows.Count];
                for (int i = 0; i < RuntimeConfig.Conditions.Rows.Count; i++)
                {
                    DataRow row = RuntimeConfig.Conditions.Rows[i];
                    if (string.IsNullOrEmpty(row[0].ToString()))
                        break;
                    int index = int.Parse(row["Index"].ToString());
                    string code = row["Code"].ToString();
                    string text = row["Message"].ToString();
                    int st = int.Parse(row["Station"].ToString());
                    int pr = int.Parse(row["Port"].ToString());
                    int bit = int.Parse(row["Bit"].ToString());
                    int priority = 0;
                    string hardware = string.Empty;
                    string comments = string.Empty;
                    if (errorprioritysupport)
                    {
                        priority = int.Parse(row["Priority"].ToString());
                        hardware = row["Hardware"].ToString();
                        comments = row["Comments"].ToString();
                    }
                    conditions[index] = new Machine_Err(code, text, st, pr, bit, priority, hardware, comments);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public static void Init()
        {
            try
            {
                string modulePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName);
                FileInfo IODescriptionFile = new FileInfo("Geely_TempTester_Description.dll");
                FileInfo XLSLoaderFile = new FileInfo("cfg\\IO_Config.xls");
                if (IODescriptionFile.LastWriteTime < XLSLoaderFile.LastWriteTime)
                {
                    RefrenceTagFileCreator IOCreator = new RefrenceTagFileCreator("IPTE.Manager");
                    IOCreator.AddClass("DiaTablePorts");
                    InitScanPorts(IOCreator["DiaTablePorts"]);
                    IOCreator.AddClass("PCICardIO");
                    InitPCICardIO(IOCreator["PCICardIO"]);
                    IOCreator.CompileCSharpCode("Geely_TempTester_Description.dll", "/keyfile:IPTE_SH_Public.snk /doc:Geely_TempTester_Description.xml", new string[] { "IOAssign.dll" }, true);
                }
                else
                {
                    InitScanPorts();
                    InitPCICardIO();
                }

                InitFunctions("DiaTableFunctions");
                InitInsulationTest();

                if (RuntimeConfig.Errors == null)
                {
                    return;
                }
                errors = new Machine_Err[RuntimeConfig.Errors.Rows.Count];
                for (int i = 0; i < RuntimeConfig.Errors.Rows.Count; i++)
                {
                    DataRow row = RuntimeConfig.Errors.Rows[i];
                    if (string.IsNullOrEmpty(row[0].ToString()))
                        break;
                    int index = int.Parse(row["Index"].ToString());
                    string code = row["Code"].ToString();
                    string text = row["Message"].ToString();
                    int st = int.Parse(row["Station"].ToString());
                    int pr = int.Parse(row["Port"].ToString());
                    int bit = int.Parse(row["Bit"].ToString());
                    int priority = 0;
                    string hardware = string.Empty;
                    string comments = string.Empty;
                    //if (errorprioritysupport)
                    //{
                    priority = int.Parse(row["Priority"].ToString());
                    hardware = row["Hardware"].ToString();
                    comments = row["Comments"].ToString();
                    //}
                    errors[index] = new Machine_Err(code, text, st, pr, bit, priority, hardware, comments);
                }

                conditions = new Machine_Err[RuntimeConfig.Conditions.Rows.Count];
                for (int i = 0; i < RuntimeConfig.Conditions.Rows.Count; i++)
                {
                    DataRow row = RuntimeConfig.Conditions.Rows[i];
                    if (string.IsNullOrEmpty(row[0].ToString()))
                        break;
                    int index = int.Parse(row["Index"].ToString());
                    string code = row["Code"].ToString();
                    string text = row["Message"].ToString();
                    int st = int.Parse(row["Station"].ToString());
                    int pr = int.Parse(row["Port"].ToString());
                    int bit = int.Parse(row["Bit"].ToString());
                    int priority = 0;
                    string hardware = string.Empty;
                    string comments = string.Empty;
                    //if (errorprioritysupport)
                    //{
                    priority = int.Parse(row["Priority"].ToString());
                    hardware = row["Hardware"].ToString();
                    comments = row["Comments"].ToString();
                    //}
                    conditions[index] = new Machine_Err(code, text, st, pr, bit, priority, hardware, comments);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("IOConfig:"+ex.Message);
            }
        }
        public RunTimeDB()
        {

        }
        
        private static Hashtable plcIO = new Hashtable();
        public static Hashtable PlcIO
        {
            get { return RunTimeDB.plcPorts; }
        }
        private static Hashtable plcFuncs = new Hashtable();
        public PLC_Cell GetPLCCells(string cellName)
        {
            return plcPorts[cellName] as PLC_Cell;
        }
        public PLCBitCell GetPLCBitCell(string cellName)
        {
            return plcPorts[cellName] as PLCBitCell;
        }
        public PLCWordCell GetPLCWordCell(string cellName)
        {
            return plcPorts[cellName] as PLCWordCell;
        }
        public PLCWordArrayCell GetPLCWordArrayCell(string cellName)
        {
            return plcPorts[cellName] as PLCWordArrayCell;
        }
        public StringValueList<PLC_Cell> GetStationInputs(string stationName)
        {
            StringValueList<PLC_Cell> res = new StringValueList<PLC_Cell>();
            string modName = stationName + "Input";
            foreach (DictionaryEntry d in plcPorts)
            {
                PLC_Cell c = d.Value as PLC_Cell;
                if (c.ModName.IndexOf(modName) >= 0)
                    res.Add(c);
            }
            res.Sort(CompareModName);
            return res;
        }
        public StringValueList<PLC_Cell> GetStationOutputs(string stationName)
        {
            StringValueList<PLC_Cell> res = new StringValueList<PLC_Cell>();
            string modName = stationName + "Output";
            foreach (DictionaryEntry d in plcPorts)
            {
                PLC_Cell c = d.Value as PLC_Cell;
                if (c.ModName.IndexOf(modName) >= 0)
                    res.Add(c);
            }
            res.Sort(CompareModName);
            return res;
        }
        public StringValueList<PLC_Cell> GetStationIO(string stationName)
        {
            StringValueList<PLC_Cell> res = new StringValueList<PLC_Cell>();
            string modName = stationName + "Input";
            string outMod = stationName + "Output";
            foreach (DictionaryEntry d in plcPorts)
            {
                PLCBitCell c = d.Value as PLCBitCell;
                if (c == null)
                    continue;
                if ((c.ModName.IndexOf(modName) >= 0) || (c.ModName.IndexOf(outMod) >= 0))
                    res.Add(c);
            }
            res.Sort(CompareModName);
            return res;
        }
        public StringValueList<PLC_Cell> GetPLCCellsByModel(string modName)
        {
            StringValueList<PLC_Cell> res = new StringValueList<PLC_Cell>();
            foreach (DictionaryEntry d in plcPorts)
            {
                PLC_Cell c = d.Value as PLC_Cell;
                if (c == null)
                    continue;
                if ((c.ModName.IndexOf(modName) >= 0))
                    res.Add(c);
            }
            res.Sort(CompareModName);
            return res;
        }
        private int CompareModName(PLC_Cell c1, PLC_Cell c2)
        {
            return string.Compare(c1.ModName, c2.ModName);
        }
        public PLC_Func GetFuncs(string funcName)
        {
            return plcFuncs[funcName] as PLC_Func;
        }
        public bool GetPLCIOIndexByName(string portname, out string portaddr, out string bitindex)
        {
            portaddr = "";
            bitindex = "";
            bool success = false;

            if (plcPorts[portname] != null)
            {
                int[] data = (int[])plcPorts[portname];

                portaddr = data[0].ToString("000");
                bitindex = data[1].ToString();
                success = true;
            }

            return success;
        }
        public bool GetPLCIOAddrByName(string portname, out PLC_Cell cell)
        {
            bool success = false;

            cell = null;
            if (plcPorts[portname] != null)
            {
                cell = (PLC_Cell)plcPorts[portname];
                success = true;
            }

            return success;
        }

        private static Hashtable pciCardIO = new Hashtable();
        public static Hashtable PciCardIO
        {
            get { return RunTimeDB.pciCardIO; }
        }
        public StringValueList<PCICardDIO> GetPCICardIOByModel(string modName)
        {
            StringValueList<PCICardDIO> res = new StringValueList<PCICardDIO>();
            foreach (DictionaryEntry d in pciCardIO)
            {
                PCICardDIO c = d.Value as PCICardDIO;
                if (c == null)
                    continue;
                if ((c.ModName.IndexOf(modName) >= 0))
                    res.Add(c);
            }
            res.Sort(ComparePCIModName);
            return res;
        }
        private int ComparePCIModName(PCICardDIO c1, PCICardDIO c2)
        {
            return string.Compare(c1.ModName, c2.ModName);
        }
        public static PCICardDIO GetPCICardIO(string cellName)
        {
            return pciCardIO[cellName] as PCICardDIO;
        }
    }



    [FlagsAttribute]
    public enum PLC_Error : ulong
    {
        OK = 0,
        Clamp_Cylinder_Out_Error = 1,
        Clamp_Cylinder_In_Error = 2,
        Support_Cylinder_In_Error = 4,
        Support_Cylinder_Out_Error = 8,
        EEProm_Cylinder_In_Error = 16,
        EEProm_Cylinder_Out_Error = 32,
        Vision_Cylinder_Left_Error = 64,
        Vision_Cylinder_Right_Error = 128,
        Pressfit_TypeB_Fault = 256,
        Turntable_Postion_Error = 256 * 2,
        Pressfit_Not_Ready = 512 * 2,
        Pressure_Too_Low = 1024 * 2,
        Index_Alarm = 4096,
        Emerg_Stop = 4096 * 2,
        Press_Emerg_Stop = 4096 * 4,
        Station2_Door_Open = 4096 * 16,
        Station3_Door_Open = 4096 * 32,
        Station4_Door_Open = 4096 * 64,
    }


    public enum Robot_Mode
    {
        Unkown = -1,
        Auto,
        Manual,
        Step,
        Error,
        SelfTest,
        Idle,
        Init
    }

}
